import java.util.ArrayList;
import java.util.Comparator;
import java.util.Iterator;


public class Group<T extends ContactItem> implements ContactItem {
	private String name;
	private ArrayList<T> entries;
	
	Group(String n){
		entries = new ArrayList<T>();
		name = n;
	}
	
	Group(String n, ArrayList<T> u){
		entries = u;
		name = n;
	}
	
	public String getName() { return name; }
	
	public ContactItem add(T cd){
		Iterator<T> it = entries.iterator();
		ContactComperator c = new ContactComperator();
		T ci;
		int i=0;
		boolean stop = true;
		while (it.hasNext() && stop){
			ci = it.next();
			if (c.compare(cd, ci) <= -1)
				stop = false;
			else
				i++;
		}
		entries.add(i,cd);
		return cd;
	}

	public T getContact(int index){
		return entries.get(index);
	}
	
	public ContactItem[] getByName(String name){
		ArrayList<T> ar = new ArrayList<T>();
		Iterator<T> i = entries.iterator();
		T cd;
		while (i.hasNext()){
			cd = i.next();
			if (cd.getName().equals(name)){
				ar.add(cd);
			}
		}
		return (ContactItem[]) ar.toArray(new Object[ar.size()]);
	}
	
	
	public String toString(){
		String s = "Gruppe : "+ name + " Eintraege : " + entries.size();
		Iterator<T> i = entries.iterator();
		while(i.hasNext())
			s += "\n    |- " +i.next().toString(); 
		return s;
	}
	
	
	
private class ContactComperator implements Comparator<ContactItem>{

		Person<?> p;
		Person<?> o;

		public int compare(ContactItem a, ContactItem b) {
			
			
			if (a instanceof Person){		
				if (b instanceof Group)			
					return -1;						// a is a person, b is a group, a is smaller than b
				if (b instanceof Person){			// a is a person, b is a person
					p = (Person<?>) a;
					o = (Person<?>) b;
					int i = p.getName().compareTo(o.getName());  			// i is the retult of the compare of the lastnames	
					if (i == 0) {
						i =p.getFirstName().compareTo(o.getFirstName()); // i is the result of the compare of the firstnames	
						
						if (i == 0){									
							if (p.getTitle().length() > o.getTitle().length())
								i = -1;			
							if (p.getTitle().length() == o.getTitle().length())
								i= 0;			
							if (p.getTitle().length() < o.getTitle().length())
								i= 1;			
						}
					}
					return i;
				}
			}
			else{
				if (a instanceof Group){
					if (b instanceof Person){
						return 1;		// a is a group, b is a person, a is greater than b
					}
					if (b instanceof Group){	// a and b are groups check the names

						return a.getName().compareTo(b.getName());
					}
				}
			}
			return 0;	// a and b are of a unkown type
		}
	}
}
